package student;

import java.sql.*;

import student.DBTest;

public class DBTest {

	public static void main(String[] args) throws Throwable, Exception {
//		insertBook();
		liststudent();
		
		
	}


	private static void liststudent() throws ClassNotFoundException, SQLException {
		Connection conn = connectDatabase();
		String selectSql = "select *from tb_student"; // 娣诲姞鍥句功淇℃伅鐨凷QL璇彞
		
		PreparedStatement ps = conn.prepareStatement(selectSql);
		 ResultSet rs = ps.executeQuery(selectSql); 
		 while(rs.next()) {
			 System.out.println("id:"+rs.getString(1)+", 涔﹀悕鏄細"+rs.getString(2));
		 }
		
	}

	/**
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 * 
	 */
	private static void insertstudentbean() throws ClassNotFoundException, SQLException {
		studentbean stu = new studentbean();
		
		stu.setId(1);
		stu.setName("JSP缂栫▼");
		stu.setAge(100);
		stu.setSex(4);
		
		Connection conn = connectDatabase();
		String insertSql = "insert into tb_student(name,id,sex,age) values(?,?,?,?)"; // 娣诲姞鍥句功淇℃伅鐨凷QL璇彞
		
		PreparedStatement ps = conn.prepareStatement(insertSql); // 鑾峰彇PreparedStatement

		ps.setString(1, stu.getName()); // 瀵筍QL璇彞涓殑绗�1涓弬鏁拌祴鍊�
		ps.setDouble(2, stu.getId()); // 瀵筍QL璇彞涓殑绗�2涓弬鏁拌祴鍊�
		ps.setInt(3, stu.getSex()); // 瀵筍QL璇彞涓殑绗�3涓弬鏁拌祴鍊�
		ps.setInt(4, stu.getAge()); // 瀵筍QL璇彞涓殑绗�4涓弬鏁拌祴鍊�
		int row = ps.executeUpdate(); // 鎵ц鏇存柊鎿嶄綔锛岃繑鍥炴墍褰卞搷鐨勮鏁�
		if (row > 0) { // 鍒ゆ柇鏄惁鏇存柊鎴愬姛
			System.out.print("鎴愬姛娣诲姞浜� " + row + "鏉℃暟鎹紒"); // 鏇存柊鎴愯緭鍑轰俊鎭�
		}
		ps.close(); // 鍏抽棴PreparedStatement锛岄噴鏀捐祫婧�
		conn.close(); // 鍏抽棴Connection锛岄噴鏀捐祫婧�

	}

	/**
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private static Connection connectDatabase() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver"); // 鍔犺浇鏁版嵁搴撻┍鍔紝娉ㄥ唽鍒伴┍鍔ㄧ鐞嗗櫒
		String url = "jdbc:mysql://localhost:3306/jsp";// 鏁版嵁搴撹繛鎺ュ瓧绗︿覆
		String username = "root"; // 鏁版嵁搴撶敤鎴峰悕
		String password = "root"; // 鏁版嵁搴撳瘑鐮�
		Connection conn = DriverManager.getConnection(url, username, password); // 鍒涘缓Connection杩炴帴
		return conn;
	}

}
